package com.xes.attend.scheduler.impl;


import com.xes.attend.config.ServerConfig;
import com.xes.attend.domain.AttendData;
import com.xes.attend.domain.AttendResult;
import com.xes.attend.domain.BaseException;
import com.xes.attend.repo.AttendDataDao;
import com.xes.attend.scheduler.Scheduler;
import com.xes.attend.service.AttendDataService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.assertj.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.Date;
import java.util.List;


/***
 * @description 下载预考勤数据调度任务
 * @author wjl
 * @ClassName: DownloadAttendSchedulerService
 * @Version 版本
 * @ModifiedBy wjl
 * @Copyright ers
 * @date 2015年11月26日 上午11:46:05
 */
@Service
public class DownloadAttendByTodaySchedulerService implements Scheduler {
	private static final Logger log = LogManager.getLogger(DownloadAttendByTodaySchedulerService.class);
	@Autowired
	private ServerConfig config;
	@Autowired
	private AttendDataDao attendDataDao;
	@Autowired
	private AttendDataService attendDataService;

	@Override
	@Scheduled(cron = "0 */3 6-22 * * *")	// 每天6点-22点每10分钟
	public void execute() {
		Date today = new Date();
		// 跨天清除旧数据
		if (DateUtil.dayOfMonthOf(today) != DateUtil.dayOfMonthOf(config.getAttendDay())) {
			log.info("清除旧的考勤数据");
			attendDataDao.deleteAll();
			config.setDownloadAttendByToday(false);
			config.setAttendDay(today);
		}
		// 今日数据是否已经下载
		long allcount = attendDataDao.countByIsDelete(0);
		if (config.getDownloadAttendByToday() == true || allcount > 0) {
			List<AttendData> attendData = attendDataDao.findFirstByIsDelete(0);
			if (DateUtil.dayOfMonthOf(today) != DateUtil.dayOfMonthOf(attendData.get(0).getClassDate())) {
				log.info("清除旧的考勤数据");
				attendDataDao.deleteAll();
				config.setDownloadAttendByToday(false);
				config.setAttendDay(today);
			} else {
				config.setDownloadAttendByToday(true);
				log.info("预考勤数据已经下载，共有考勤数据:{}", allcount);
				return;
			}
		}

		StopWatch stopWatch = new StopWatch("预考勤数据下载服务VenueId：" + config.getVenueId());
		stopWatch.start("预考勤数据下载");
		log.info("预考勤数据下载开始");
		AttendResult attendResult = null;
		try {
			attendResult = attendDataService.downloadAttendDataByToday(config.getVenueId());
		} catch (BaseException e) {
			log.error("预考勤数据下载失败:{}:{}", e.getResultCode(), e.getMessage());
		}
		log.info("预考勤数据今日共计下载:{}条", attendResult.getDataCount());
		stopWatch.stop();
		log.debug(stopWatch.prettyPrint());
		if (attendResult.getDataCount() > 0) {
			config.setDownloadAttendByToday(true);
			config.setAttendDay(today);
		}
	}

}
